<!-- m_materiel_tticar.ftl 天天爱车产品 -->
var MMaterielTticar = {
    u: '/mMaterielTticar',
    uSaveSubmit: '/mMateriel/saveSubmit'
    , uList: '/tticar/goodsList'
    // , uEdit: '/mMaterielTticar/edit'
    , uEdit: '/tticar/goods'
    , uDel: '/mMaterielTticar/delete'
    , uGetSku: '/tticar/getSku'
    , uIsOnLine: '/tticar/isOnline'
    , uCancel: '/mMaterielTticar/cancelRelative'
    , uSearch: '/tticar/search'
    , uRelative: '/tticar/relativeSku'
    , uSave: '/tticar/save'
    , uGoodsMessage: '/tticar/getGoodsMessage'
    , comboPageUrl: 'tticar/comboPage'
};

MMaterielTticar.dg = function () {
    var grid = new $yd.DataGrid(this.dtable);
    grid.fitColumns = true;
    // grid.onDblClickRow = function (index, row) {
    //     GoodsOrder._edit(row['id']);
    // };
    grid.onClickRow=function (rowIndex, rowData) {
        $(this).datagrid('unselectRow', rowIndex);
    }
    grid.rownumbers = true;
    grid.url = MMaterielTticar.uList; //tt
    // grid.nowrap = false;
    grid.columns = [[
        // {field: 'id', checkbox: true}
        // ,
        {
            field: 'name', title: '产品名称', width: 150, formatter: function (value, row, index) {
                var value = '<div style="font-family: 微软雅黑;font-size: 12px;font-weight: 700">' + value + '</div>';
                // if (row['mpic']) value = '<div><img src="' + $.urlPre + row['mpic'] + '"></div>' + value;
                return value;
            }, styler: function () {
                return {class: 'goods-name'};
            }
        }
        // , {field: 'id', title: '规格', width: 80}
        , {field: 'id', title: 'id', width: 80,hidden:true}
        // , {field: 'inventory', title: '虚拟库存', width: 80}
        , {field: 'storeName', title: '所属店铺', width: 80}
        , {field: 'status', title: '上架状态', width: 50,formatter:function (value, row) {
            var str = row.id.substring(0,10) ;
            str = str+"";
            var str1 ="1"+ row.id.substring(10,row.id.length);

            if (value == 0) {
                return '上架';
            }else if (value == 1) {
                return '下架';
            }else {
                return '';
            }
        }}
        , {field: 'relativeStatus', title: '操作', width: 110,formatter:function (value, row) {
            var returnBtn = '';
            var str = row.id.substring(0,10) ;
            str = str+"";
            var str1 ="1"+ row.id.substring(10,row.id.length); //#FF3300
            var name ="'"+ row['name'] +"'";
            if (row['status'] == 0) {
                returnBtn += '<button onmouseover="this.style.backgroundColor=\'#E39300\'" onmouseout="this.style.backgroundColor=\'#FF3300\'" style="width:82px;background-color: #FF3300;border-radius:2px;color:white;border: 0px;" href="#" onclick="MMaterielTticar.isOnline('+str+','+str1+','+1+','+name+')">下架</button>&nbsp;&nbsp;' ;
            }else if (row['status'] == 1) {
                returnBtn += '<button  onmouseover="this.style.backgroundColor=\'#E39300\'" onmouseout="this.style.backgroundColor=\'#FF3300\'" style="width:82px;background-color: #FF3300;border-radius:2px;color:white;border: 0px;" href="#" onclick="MMaterielTticar.isOnline('+str+','+str1+','+0+','+name+')">上架</button>&nbsp;&nbsp;' ;
            }


            if (value == 0) {
                returnBtn += '<button onmouseover="this.style.backgroundColor=\'#E39300\'" onmouseout="this.style.backgroundColor=\'#0099FF\'" style="width:82px;background-color: #0099FF;border-radius:2px;color:white;border: 0px;" href="#" onclick="MMaterielTticar._saveAsInv('+str+','+str1+')">保存为存货</button>&nbsp;&nbsp;';
            }
                // return '';
                returnBtn +=  '<button  onmouseover="this.style.backgroundColor=\'#E39300\'" onmouseout="this.style.backgroundColor=\'#00BE67\'" style="width:82px;background-color:#00BE67; border-radius:2px;color:white;border: 0px;" href="#" onclick="MMaterielTticar._edit('+str+','+str1+')">编辑</button>';


            return returnBtn;

        }}

    ]];
    grid.view = detailview;
    grid.detailFormatter = function (rowIndex, rowData) {
        return '<table></table>';
    };
    grid.onExpandRow = function (index, row) {
        var $td = $(this).datagrid('getRowDetail', index).find('table');

        $td.datagrid({

            url: MMaterielTticar.uGetSku + "?id=" + row['id'],
            method: 'get',
            // fitColumns: true,
            rownumbers: true,
            columns: [[
                {field: 'goodsId', title: 'goodsId', width: 200,hidden:true},
                {field: 'skuValue', title: 'skuValue', width: 100,hidden:true},
                {field: 'skuName', title: '规格名称', width: 300},
                {field: 'inventory', title: '虚拟库存', width: 100},
                {field: 'relativeStatus', title: '是否关联', width: 150,formatter:function (value, row) {
                   if (value == 0) {
                       return '未关联' ;
                   }else if (value ==1 && row['combo']==0) {
                       return '已关联';
                   }else if (value ==1 && row['combo']==1) {
                       return '已关联'+'<span style="color: red">(套餐)</span>';
                   }
                }},
                {field:'operate',title:'操作',width:200,formatter:function (value,row) {
                    if (row['relativeStatus'] == 0) {
                        var str = row.goodsId.substring(0,10) ;
                        str = str+"";
                        var str1 ="1"+ row.goodsId.substring(10,row.goodsId.length);
                        var skuValue = "'" +row.skuValue +"'";

                        return '<button onmouseover="this.style.backgroundColor=\'#E39300\'" onmouseout="this.style.backgroundColor=\'#FEA500\'" style="background-color: #FEA500;border-radius:2px;color:white;border: 0px;" href="#" ' +
                            'onclick="MMaterielTticar.relativeInv('+str+','+str1+','+skuValue+')">关联</button>&nbsp;&nbsp;'+
                        '<button  onmouseover="this.style.backgroundColor=\'#E39300\'" onmouseout="this.style.backgroundColor=\'#66CC99\'" style="background-color: #66CC99;border-radius:2px;color:white;border: 0px;" href="#" ' +
                        'onclick="MMaterielTticar.relativeInvCombo('+str+','+str1+','+skuValue+')">关联套餐</button>&nbsp;&nbsp;';
                    }
                }}
            ]],
            onClickRow : function (rowIndex,rowData) {
                $(this).datagrid('unselectRow', rowIndex);
                MMaterielTticar.newSkutable.datagrid("reload", {
                    tticarGoodsId: rowData.goodsId,
                    skuValue: rowData.skuValue,
                   
                });

            },
            onResize: function () {
                MMaterielTticar.dtable.datagrid('fixDetailRowHeight', index);
            },
            onLoadSuccess: function () {

                setTimeout(function () {
                    MMaterielTticar.dtable.datagrid('fixDetailRowHeight', index);
                }, 0);
            }
        });
    };
    grid.onLoadSuccess = function() {
        // 默认打开全部
        // var row = $('#mMaterielTticar_table').datagrid("getRows");
        // for (var r = 0; r < row.length; r++) {
        //     $('#mMaterielTticar_table').datagrid("expandRow",r);
        // }

    };

    grid.loadGrid();
};
MMaterielTticar.dg.getOne = function () {
    var sels = MMaterielTticar.dg.getSels();
    if (sels.length === 1) {
        return sels[0];
    }
    return null;
};
MMaterielTticar.dg.getSels = function () {
    return MMaterielTticar.dtable.datagrid('getSelections');
};
// 处理按钮
MMaterielTticar.btn = function () {
    var sb = new $yd.SearchBtn($(MMaterielTticar.obtn));
    // sb.create('remove', '下架', MMaterielTticar.remove);
    sb.create('refresh', '刷新', MMaterielTticar.refreshByButton);
    // sb.create('edit', '编辑', MMaterielTticar.edit);
    sb.create('plus', '新增', MMaterielTticar.plus);
    // sb.create('search', '查询', MMaterielTticar.search);
};
//上下架
MMaterielTticar.isOnline = function (str,str1,status,name) {
    var str2 = str1+"";
    str2 = str2.substring(1, str2.length);
    var id = str+""+str2;
    var msg = '';
    if (status == 1) {
        msg = "下架商品后，平台上将不展示商品信息，客户无法下单购买，仍确认下架？"
    }else if (status ==0) {
        msg = "确认上架商品" + name +"？";
    }
    $yd.confirm(msg,function () {
        $yd.post(MMaterielTticar.uIsOnLine, {id: id,status:status}, function () {
            MMaterielTticar.refresh();
        });
    })
};

//关联存货
MMaterielTticar.relativeInv = function (str,str1,skuValue) {
    // var href = "tticar/searchRelative?goodsId="+goodsId+"&order="+order+"&id="+id;
    // href= "/mMateriel/searchDgNew?goodsId="+goodsId+"&order="+order+"&id="+id;
    // var $dg = $yd.win.create('商品', href);
    // $dg.width = "1050px;";
    // $dg.height = "400px;";
    // $dg.open(function (that, $win) {
    //
    //     }, function (that, $win) {
    //         MMaterielTticar.relativeInvSubmit(id,status);
    //     }, function () {
    //     }
    // );

    var str2 = str1+"";
    str2 = str2.substring(1, str2.length);
    var goodsId = str+""+str2;
    $yd.win.create('商品', "/mMateriel/searchDgNew?goodsId="+goodsId+"&skuValue="+skuValue).open(function (that, $win) {
            // GoodsOrder.preForm();
            // $yd.get("/mMateriel/searchDgNew?goodsId="+goodsId+"&order="+order+"&id="+id, function (data) {
            //     $win.find('form').form('load', data);
            // })
        }
        , function (that, $win) {
            var goodsId = $("#orderCode").val();
            var order = $("#order").val();
            var id = $("#id").val();
            var data = Goods.getChecked();
            $("#data").val(data[0].skuId)
            $yd.form.create($win.find('form')).url(MMaterielTticar.uRelative,{goodsId:goodsId,order:order,id:id,data:data}).submit(function () {
                that.close();
                MMaterielTticar.refresh();
            });
        })
};

//套餐关联窗口  relativeInvCombo
MMaterielTticar.relativeInvCombo = function (str,str1,skuValue) {
    var str2 = str1+"";
    str2 = str2.substring(1, str2.length);
    var goodsId = str+""+str2;
    
    var href = MMaterielTticar.comboPageUrl;
    var dg = $yd.win3.create('关联套餐', href + "?goodsId="+goodsId+"&skuValue="+skuValue);
    dg.width = "70%";
    dg.height = "50%";
    dg.open(function (that, $win) {

    });
};


//
MMaterielTticar.edit = function () {
    var sel = MMaterielTticar.dg.getOne();
    if (!sel) {
        $yd.alert('请选择一条记录');
        return;
    }
    MMaterielTticar._edit(sel['id'])
};
// 表单预处理
MMaterielTticar.preForm = function ($form) {
    new $yd.combogrid('#brandId').addCol('name', "品牌").load("/tticar/brand");
    new $yd.combobox('ttstoreId').load("/wStore/select");
    // 分类
    var $categoryId = new $yd.combotreegrid('#categoryId').addCol('name', "分类");
    $categoryId.pagination = false;
    $categoryId.loadFilter = function (data) {
        return data;
    };
    $categoryId.load("/tticar/category");
    // 图片详情
    MMaterielTticar._picDesc = new $yd.picDesc('#pic_desc_container');
    // 存货选择
    var $materiel = new $yd.combogrid("#materielId");
    $materiel.addCol('name', '产品名称').addCol('code', '编码').addCol('categoryName', '分类').addCol('brandName', '品牌')
        .addCol('isTticar', '已添加', {
            formatter: function (value, row, index) {
                if (value > 0 || row.tticar_goods_id != null) {
                    return '<label class="label label-sm label-primary">已添加</label>';
                } else {
                    return '<label class="label label-sm label-warning">未添加</label>';
                }
            }
        });
    $materiel.onSelect = function (value, row, index) {
        var g = $('#materielId').combogrid('grid').datagrid('getSelected');
        $("#materielIdForSubmit").val(g.id);
        if (g['isTticar'] > 0 || row.tticar_goods_id != null) {
            $('#materielIdForSubmit').combogrid('clear');
            return;
        }
        // $form.find('#categoryName').textbox('setText', g['categoryName']);
        $form.find('#name').textbox('setValue', g['name']);
        // $form.find('#brandName').textbox('setValue', g['brandName']);
        initSkuTabData(g); // 价格体系
        console.log(g['pictures'])
        MMaterielTticar.pictrues = new $yd.fileinput('#pictrues').render(g['pictures']); //主图
        MMaterielTticar._picDesc.setValue(g['description']);
    };
    $materiel.load("/mMateriel/m/list");
    // sku
    var $sukTable = $('#sukTable'), editIndex = -1;
    initSkuTab();

    function initSkuTabData(g) {
        try {
            $sukTable.datagrid('rejectChanges');
        } catch (e) {
        }
        $.each(g['mSkus'], function (i, n) {
            var prices = JSON.parse(n.prices);
            if (n.inventory ==null || n.inventory ==undefined || n.inventory=='') {
                n.inventory =1;
            }
            $sukTable.datagrid('appendRow', {id: n.id, name: n.skus,price:prices[0], pricesell:n.sellPrice ,pricemember:prices[0],
                pricevip:prices[1],pricevip2:prices[2],pricevip3:prices[3],skuPic: n.img, inventory: n.inventory});
        })
    }

    function initSkuTab() {
        $sukTable.datagrid({
            fitColumns: true,
            autoRowHeight: true,
            rownumbers: true,
            singleSelect: true,
            nowrap:false,
            columns: [[
                {field: 'skuId', checkbox: true},
                {field: 'name', title: '规格型号', width: 80,editor:{type:'text'}},
                {field: 'inventory', title: '虚拟库存', width: 80,editor: {type: 'numberbox', options: {default: 1}}}
                // , {field: 'inventory', title: '规格库存', width: 80, editor: {type: 'numberbox', options: {precision: 0}}}
                , {field: 'price', title: '进价', width: 80,hidden:true, editor: {type: 'numberbox', options: {precision: 2}}}
                , {field: 'pricesell', title: '零售价', width: 80, editor: {type: 'numberbox', options: {precision: 2}}}
                , {field: 'pricemember', title: '批发价', width: 80, editor: {type: 'numberbox', options: {precision: 2}}}
                , {field: 'pricevip', title: '会员价1', width: 80, editor: {type: 'numberbox', options: {precision: 2}}}
                , {
                    field: 'pricevip2',
                    title: '会员价2',
                    width: 80,
                    editor: {type: 'numberbox', options: {precision: 2}}
                }
                , {
                    field: 'pricevip3',
                    title: '会员价3',
                    width: 80,
                    editor: {type: 'numberbox', options: {precision: 2}}
                }
   
                , {
                    field: 'skuPic', title: '图片', width: 80,hidden:true, formatter: function (value, row, index) {
                        if (value) return '<img src="' + $.urlPre + value + '" style="height: 32px;">';
                        return "";
                    }
                },
                {field: 'isRelative', title: '关联存货状态', width: 80,},
                {field: 'goodsIdString', title: 'goodsIdString', width: 80,hidden:true}

            ]],
            toolbar: [

                {text: '增加', iconCls: 'icon-add', handler: appendRow1},
                {
                    text: '移除', iconCls: 'icon-remove', handler: function () {
                    // if (editIndex == -1) return;
                    // $sukTable.datagrid('cancelEdit', editIndex).datagrid('deleteRow', editIndex);
                    // editIndex = -1;
                    var deleteRow =  $sukTable.datagrid('getChecked');
                    if(deleteRow.length == 0) {
                        $yd.alert("选中记录");
                        return;
                    }
                    var arr = [];
                    for(var i=0; i<deleteRow.length; i++) {
                        arr[i] = deleteRow[i].name;
                    }
                    for(var j=0; j<arr.length; j++) {
                        var name = arr[j];
                        var rows = $sukTable.datagrid("getRows");
                        for(var i=rows.length-1; i>=0; i--) {
                            if(rows[i].name == name) {
                                if (rows[i].isRelative == "已关联"){
                                    $yd.confirm("该规格已关联存货，若移除将会删除整个产品的关联关系，确认删除？",function () {
                                        var goodsId = rows[i].goodsIdString;
                                        $sukTable.datagrid("deleteRow", i);
                                        $yd.post("/mMaterielTticar/deleteRelative", {goodsId: goodsId}, function () {

                                        });
                                    })
                                    return;
                                }else {
                                    $sukTable.datagrid("deleteRow", i);
                                }


                                // return;
                            }
                        }
                    }

                }
                },
                {
                    text: '确定', iconCls: 'icon-save', handler: function () {
                    $sukTable.datagrid('acceptChanges').datagrid('clearSelections');
                }
            //     }, {
            //         text: '移除', iconCls: 'icon-remove', handler: function () {
            //             if (editIndex == -1) return;
            //             $sukTable.datagrid('cancelEdit', editIndex).datagrid('deleteRow', editIndex);
            //             editIndex = -1;
            //         }
                }],
            onClickCell: function (index, field) {
                if (editIndex != index) {
                    if (editIndex > -1) {
                        $(this).datagrid('endEdit', editIndex);
                    }
                    editIndex = index;
                }
                $(this).datagrid('beginEdit', index);
                var ed = $(this).datagrid('getEditor', {index: index, field: field});
                if (ed) {
                    ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
                }
            },
            onClickRow:function (rowIndex, rowData) {
            $(this).datagrid('unselectRow', rowIndex);
        }

        });
    }
    function appendRow1() {
        if (editIndex > -1) {
            $sukTable.datagrid('acceptChanges').datagrid('cancelEdit', editIndex);
        }
        $sukTable.datagrid('appendRow', {inventory: 1}).datagrid('clearSelections');
        editIndex = $sukTable.datagrid('getRows').length - 1;
        $sukTable.datagrid('beginEdit', editIndex);
        var ed = $sukTable.datagrid('getEditor', {index: editIndex, field: 'skus'});
        if (ed) {
            ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
        }
    }
};
MMaterielTticar.preSub = function (param) {

    $('#sukTable').datagrid('acceptChanges').datagrid('clearSelections');
    var rows = $('#sukTable').datagrid('getRows'), isPre = false,inventoryBoo = false, inventory = 0, detail = {}, spec = [], _list = [];
    $.each(rows, function (i, n) {
        inventory += parseFloat(n['inventory']);
        if (!n['pricemember']) {
            isPre = true;
        }
        if (!n['inventory']){
            inventoryBoo = true;
        }
        n['price'] = null;
        detail[i + 1] = cloneSpec(n);
        _list.push({id: i + 1, name: n['name']});
        param.pricemember = n['pricemember'];
        param.maxPricemember = n['maxPricemember'];
    });
    spec.push({name: "规格", order: 1, list: _list});
    if (inventoryBoo){
        $yd.alert("请完善规格信息，库存数量是必填项.");
        return true;
    }
    if (isPre) {
        $yd.alert("请完善规格信息，批发价是必填项.");
        return isPre;
    }
    param.goodsProductionStr = JSON.stringify(rows);
    param.standardCfg = JSON.stringify({spec: spec, detail: detail});
    param.inventory = inventory;
    param.pictrues = MMaterielTticar.pictrues.getValues();
    param.description = MMaterielTticar._picDesc.getValue();

    function cloneSpec(n) {
        var _n = $.extend({}, n);
        _n['pricevipSecond'] = _n['pricevip2'];
        _n['pricevipThird'] = _n['pricevip3'];
        //
        delete _n['createtime'];
        delete _n['modifytime'];
        delete _n['goodId'];
        delete _n['id'];
        delete _n['skuId'];
        delete _n['skuPic'];
        delete _n['pricevip2'];
        delete _n['pricevip3'];
        return _n;
    }
};
MMaterielTticar._edit = function (str,str1) {
    var str2 = str1+"";
    str2 = str2.substring(1, str2.length);
    var id = str+""+str2;
    $yd.win.create('编辑天天爱车产品', MMaterielTticar.uEdit + '?id=' + id).big().open(function (that, $win) {
            var $form = $win.find('form');
            MMaterielTticar.preForm($form);
            // $form.find('#materielId,#ttstoreId').combobox('readonly');
            $form.find('#ttstoreId').combobox('readonly');
            // $form.find('#materielId').combobox('hidden');
            $('#materielId').combobox({required:false});
            $('#materielId').next(".combo").hide();
            $('#selectInv').hide();
            $yd.get(MMaterielTticar.uEdit + "/" + id, function (data) {
                $form.form('load', data);
                try {
                    $('#sukTable').datagrid('rejectChanges');
                } catch (e) {
                }
                // $.each(data['materielSkuIds'].split(','), function (i, n) {
                //     var sku = data['skus'][i];
                //     sku.id = parseInt(n);
                //     $('#sukTable').datagrid('appendRow', sku);
                // });
                $.each(data['skus'], function (i, n) {
                    var sku = data['skus'][i];
                    // sku.id = parseInt(n);
                    $('#sukTable').datagrid('appendRow', sku);
                });
                $('#categoryId').combotreegrid("setText",data['catgoryName']);

                MMaterielTticar.pictrues = new $yd.fileinput('#pictrues').renderNew(data['pictures']); //主图
                MMaterielTticar._picDesc.setValue(data['description']);
            })

        }, function (that, $win) {
            $yd.form.create($win.find('form')).pre(MMaterielTticar.preSub).url(MMaterielTticar.uEdit).submit(function () {
                that.close();
                MMaterielTticar.refresh();
            });
        }
    );
};
//新增
MMaterielTticar.plus = function () {
    var sel = MMaterielTticar.dg.getOne();
    var href = MMaterielTticar.uEdit;
    if (sel) href += '?pid=' + sel['id'] + '&name=' + sel['name'];
    $yd.win.create('新增天天爱车产品', href).big().open(function (that, $win) {
            MMaterielTticar.preForm($win.find('form'));
        }, function (that, $win) {
            $yd.form.create($win.find('form')).pre(MMaterielTticar.preSub).url(MMaterielTticar.uEdit).submit(function () {
                that.close();
                MMaterielTticar.refresh();
            });
        }
    );
};
//
MMaterielTticar.refreshByButton = function () {
    $('#mMaterielTticar_table').datagrid('unselectAll');
    $(".search-form").form('clear');
    MMaterielTticar.loadWstore();
    MMaterielTticar.dtable.datagrid('load', MMaterielTticar.sform.serializeObject());
};

MMaterielTticar.refresh = function () {
    // $('#mMaterielTticar_table').datagrid('unselectAll');
    MMaterielTticar.dtable.datagrid('reload');
};

//搜索
MMaterielTticar.search = function () {
    MMaterielTticar.dtable.datagrid('load', MMaterielTticar.sform.serializeObject());
};
// 加载店铺
MMaterielTticar.loadWstore = function () {
    var slist = new $yd.datalist(MMaterielTticar.storeList);
    slist.singleSelect = true;
    slist.checkbox = false;
    slist.onClickRow = function (index, row) {
        $("#queryStoreId").val(row.id);
        MMaterielTticar.dtable.datagrid('reload', {ttstoreId: row.id});
    };
    slist.load('/wStore/select');
};
MMaterielTticar.relativeTable = function () {
    // MMaterielTticar.relativeTable = $("#relativeGoods_table");
    var grid = new $yd.DataGrid(MMaterielTticar.newSkutable);
    grid.url ='/mMaterielTticar/relativeGoods';
    grid.columns = [[
            {title:'存货名称',field:'name',width:150},
            {title:'分类',field:'category',width:80},
        {title:'品牌',field:'brand',width:80},
        {title:'规格',field:'skuName',width:80},
        {title:'商品编码',field:'goodsCode',width:80},
        {title:'配件编码',field:'partsCode',width:80},
        {title:'使用车型',field:'suitCar',width:80},
        {title:'默认供应商',field:'supply',width:80},
        {title:'参考进价',field:'inPrice',width:60},
        {title:'参考零售价',field:'salePrice',width:60},
        {title:'对应数量',field:'comboCount',width:60},
        {title:'当前库存',field:'repositoryCount',width:60},
        {title:'skuId',field:'id',width:80,hidden:true},
        {title:'tticarGoodsId',field:'tticarGoodsId',width:80,hidden:true},
        {title:'skuValue',field:'skuValue',width:80,hidden:true},
        {field: 'skuId', title: '操作', width: 120,formatter:function (value, row) {
                var id = row['id'];
                var tticarGoodsId = "'" + row['tticarGoodsId'] + "'";
                var skuValue = "'" + row['skuValue'] + "'";
                return '&nbsp;&nbsp;&nbsp;' + '' +
                    '<button onmouseover="this.style.backgroundColor=\'#E39300\'" onmouseout="this.style.backgroundColor=\'black\'" style="background-color: black;border-radius:2px;color:white;border: 0px;" href="#" ' +
                    'onclick="MMaterielTticar.cancelRelative('+id+','+tticarGoodsId+','+skuValue+')">取消关联</button>' ;

        }}
        ]];
    grid.loadGrid();
    // MMaterielTticar.relativeTable.grid({
    //     url: '/mMaterielTticar/relativeGoods',
    //     // idField:'id',
    //     // treeField:'text',
    //     columns:[[
    //         {title:'存货skuId',field:'skuId',width:250},
    //         // {title:'库存',field:'num',width:200}
    //     ]]
    // });
}
MMaterielTticar.cancelRelative=function (id,tticarGoodsId,skuValue) {
    var msg = "取消关联商品后，线上订单将无法匹配库存商品，发货后可能造成库存量不准确，是否仍旧确认取消关联？";
    $yd.confirm(msg,function () {
        $yd.post(MMaterielTticar.uCancel, {skuId: id,tticarGoodsId :tticarGoodsId,skuValue :skuValue}, function () {
            MMaterielTticar.refresh();
            MMaterielTticar.newSkutable.datagrid('reload');
        });
    })
}

$(function () {
    MMaterielTticar.sform = $('#mMaterielTticar_form');
    MMaterielTticar.dtable = $('#mMaterielTticar_table');
    MMaterielTticar.newSkutable = $('#relativeGoods_table');
    MMaterielTticar.obtn = '#mMaterielTticar_btn';
    MMaterielTticar.storeList = $('#wstore_list');

    MMaterielTticar.dg(); // 数据表格
    MMaterielTticar.btn(); // 初始化按钮
    MMaterielTticar.relativeTable();
    $yd.bindEnter(MMaterielTticar.search);
    //
    MMaterielTticar.loadWstore();
});
var btn1 = document.getElementById("searchButton");
btn1.addEventListener("click", function() {
    $('#mMaterielTticar_table').datagrid('unselectAll');
    MMaterielTticar.dtable.datagrid('load', MMaterielTticar.sform.serializeObject());
});


MMaterielTticar._saveAsInv = function (str,str1) {
    // MMaterielTticar.dgType = "goods";
    var str2 = str1+"";
    str2 = str2.substring(1, str2.length);
    var id = str+""+str2;
    $yd.win2.create('保存为存货', MMaterielTticar.uSave + '?id=' + id).big().open(function (that, $win) {
        MMaterielTticar.win = $win;
        MMaterielTticar.winThat = that;
            $yd.get(MMaterielTticar.uGoodsMessage + "/" + id, function (data) {
                $win.find('form').form('load', data);
                MMaterielTticar.preFormSaveGoods(data,true);
                MMaterielTticar.cateChange($('input[name="categoryId"]').val());
            })
        }, function () {
        MMaterielTticar.save();
        }, function () {
        MMaterielTticar.closeDg(1);
        }
    );
};

MMaterielTticar.save = function() {
    $yd.form.create(MMaterielTticar.win.find('form')).url(MMaterielTticar.uSaveSubmit).pre(MMaterielTticar.pre).submit(function () {
        MMaterielTticar.closeDg(0);
        MMaterielTticar.refresh();
    });
};

MMaterielTticar.closeDg = function (closeEd) {
    if(closeEd == 0) {
        MMaterielTticar.winThat.close();
    }

    MMaterielTticar.dgType = undefined;
    MMaterielTticar.winThat = undefined;
    MMaterielTticar.win = undefined;
};

MMaterielTticar.cateChange = function (newValue, oldValue) {
    $('#skuContainer').html('');
    MMaterielTticar.skuIdTags = [];
    $yd.get("/mCateogry/msku?categoryId=" + newValue, function (data) {
        if (data.length == 0) {
            $('#m_tabs').tabs('unselect', 1).tabs('disableTab', 1);
            return;
        }
        $('#m_tabs').tabs('enableTab', 1);
        $.each(data, function (i, n) {
            var id = 'sku_' + n['sku_id'];
            var $input = '<div class="form-group"><label class="col-sm-2 control-label">' + n['name'] + '</label><div class="col-sm-8"><input id="' + id + '" type="text" style="width:100%;"></div></div>';
            $('#skuContainer').append($input);
            MMaterielTticar.skuIdTags.push({id: '#' + id, name: n['name']});// 存储规格标签
            $('#' + id).tagbox({
                url: '/mSkuValue/allList?status=0&skuId=' + n['sku_id'],
                valueField: 'name',
                textField: 'name',
                method: 'get',
                panelHeight: 'auto',
                prompt: '输入规格值，无规格值不能提取组合',
                // limitToList: true,
                hasDownArrow: true,
                loadFilter: function (data) {
                    $.each(data['data'], function (i, n) {
                        if (n['isDefault']) {
                            $('#' + id).tagbox('setValue', {name: n['name']});
                        }
                    });
                    return data['data'];
                }
            });
        })
    });
};


//表单预处理
MMaterielTticar.preFormSaveGoods = function (data,isPlus) {
    // MMateriel.initCategoryTree();
    if (isPlus || $("#hiddenCategoryId").val() == 0) {
        var category = new $yd.combotreegrid("#categoryId", true).addCol('name', '名称').addCol('code', '编码');
        category.onChange = MMaterielTticar.cateChange;
        category.load("/mCateogry/list?status=0");
    }

    new $yd.combogrid('#brandId').addCol('name', '名称').load('/mBrand/list?status=0');
    new $yd.combogrid('#defaultUintId').addCol('name', '名称').addCol('code', '编码').load('/wRelativeUnit/list?rproperty=2&status=0');


    var materielId = $("#id").val();
    if (materielId != null && materielId != "" && materielId != undefined) {
        $yd.post("/wPositionMateriel/getBindInfo", {materielId: materielId}, function (data) {
            if (data == "") {
                return;
            }
            var arr = data.split(",");
            var tmp = "";
            for (var i = 0; i < arr.length; i++) {
                tmp += ";" + arr[i].split("_")[1];
            }
            if (tmp != "") {
                tmp = tmp.substr(1);
            }
            $("#house").val(data);
            $("#defaultWhouseId").textbox("setValue", tmp);
        });
    }

    $("#houseSet").click(function () {
        $("#defaultWhouseId").next().find(".textbox-text").focus();//避免设置链接enter键位保存后再次触发

        MMaterielTticar.dgType2 = "kw";
        var href = "/wWearhouse/treeGridBind?materielId=" + materielId + "&house=" + $("#house").val();
        var $dg = $yd.win2.create('仓库/库位', href);
        $dg.width = "450px;";
        $dg.height = "520px;";
        $dg.addBtn("新增库位", "icon-add", function () {
            MMaterielTticar.closeDg2(0);
            MMaterielTticar.plusKw();
        });
        $dg.open(function (that, $win) {
            MMaterielTticar.win2 = $win;
            MMaterielTticar.winThat2 = that;
        }, function () {
            MMaterielTticar.saveKwSet();
        }, function () {
            MMaterielTticar.closeDg2(1);
        });
    });
    this.initPriceTab();

    //图片详情
    MMaterielTticar._picDesc = new $yd.picDesc('#pic_desc_container');

    if (data) {
        $.each(data['mSkus'], function (i, n) {
            if (n['prices']) {
                $.extend(n, JSON.parse(n['prices']));
                delete n['prices'];
            }
        });
        MMaterielTticar.ptable.datagrid('loadData', data['mSkus']);
        //图片处理.
        console.log(data['pictures'])
        MMaterielTticar.pictrues = new $yd.fileinput('#pictrues').render(data['pictures']);
        //描述
        // $('#description').texteditor('setValue', data['description']);
        MMaterielTticar._picDesc.setValue(data['description']);
    } else {
        MMaterielTticar.pictrues = new $yd.fileinput('#pictrues').render();
    }

};
//新增库位
MMaterielTticar.plusKw = function () {
    MMaterielTticar.dgType2 = "position";
    var dg = $yd.win2.create('新增库位', "/wPosition/edit");
    dg.width = "500px";
    dg.height = "400px";
    dg.open(function (that, $win) {
        MMaterielTticar.win2 = $win;
        MMaterielTticar.winThat2 = that;
            // new $yd.combotreegrid("#wearhouseId").addCol("name", "名称").addCol("code", "编码").load("/wWearhouse/listForAvailable");
        }, function () {
        MMaterielTticar.saveKw();
        }, function () {
        MMaterielTticar.closeDg2(1);
        } , function () {
        MMaterielTticar.saveKwNext();
        }
    );
};

MMaterielTticar.saveKw = function () {
    $yd.form.create(MMaterielTticar.win2.find('form')).url("/wPosition").submit(function () {
        MMaterielTticar.closeDg2(0);
    });
};
MMaterielTticar.saveKwNext = function () {
    $yd.form.create(MMaterielTticar.win2.find('form')).url("/wPosition").submit(function () {
        WPositionEdit.reset();
    });
};
MMaterielTticar.closeDg2 = function (closeEd) {
    if(closeEd == 0) {
        MMaterielTticar.winThat2.close();
    }

    MMaterielTticar.dgType2 = undefined;
    MMaterielTticar.winThat2 = undefined;
    MMaterielTticar.win2 = undefined;
};

MMaterielTticar.saveKwSet = function() {
    var data = KW.getResult();
    if (data == "") {
        $("#defaultWhouseId").textbox("setValue", "");
        $("#house").val("");
    } else {
        var arr = data.split(",");
        var tmp = "";
        for (var i = 0; i < arr.length; i++) {
            tmp += ";" + arr[i].split("_")[1];
        }
        if (tmp != "") {
            tmp = tmp.substr(1);
        }
        $("#house").val(data);
        $("#defaultWhouseId").textbox("setValue", tmp);
    }
    MMaterielTticar.closeDg2(0)
};


// 表单预处理
MMaterielTticar.initPriceTab = function () {
    if (!MMaterielTticar.initPriceTab.isInit) {
        MMaterielTticar.priceLv[0].push({
            field: 'img', title: '图片', width: 60, editor: 'upImage', formatter: function (value) {
                if (value)  return MMaterielTticar.getImg(value);
                return '';
            }
        });
        MMaterielTticar.initPriceTab.isInit = true;
    }

    drawPriceTab();
    var editIndex = -1;

    function drawPriceTab() {
        MMaterielTticar.ptable = $('#priceTab');
        MMaterielTticar.ptable.datagrid({
            fitColumns: true,
            autoRowHeight: true,
            rownumbers: true,
            singleSelect: true,
            columns: MMaterielTticar.priceLv,
            toolbar: [
                {text: '提取组合', iconCls: 'icon-reload', handler: convertSku},
                '-',
                {text: '增加', iconCls: 'icon-add', handler: appendRow},
                {
                    text: '移除', iconCls: 'icon-remove', handler: function () {
                    if (editIndex == -1) return;
                    MMaterielTticar.ptable.datagrid('cancelEdit', editIndex).datagrid('deleteRow', editIndex);
                    editIndex = -1;
                }
                },
                {
                    text: '确定', iconCls: 'icon-save', handler: function () {
                    MMaterielTticar.ptable.datagrid('acceptChanges').datagrid('clearSelections');
                }
                },
                {
                    text: '取消', iconCls: 'icon-undo', handler: function () {
                    MMaterielTticar.ptable.datagrid('rejectChanges');
                    editIndex = -1;
                }
                }],
            onClickCell: function (index, field, value) {
                if (editIndex != index) {
                    editIndex = index;
                }
                // 以前的规格名称不允许编辑
                var rows = $(this).datagrid('getRows');
                var row = rows[index];
                if (!$yd.isEmpty(row['id'])) {
                    if (field == 'skus' ) {
                        $(this).datagrid('endEdit', index);
                        $yd.alert("已存在规格名称不可修改");
                        return;
                    } else {
                        // var e = MMateriel.ptable.datagrid('getColumnOption', 'skus');
                        // e.editor = {};
                        $(this).datagrid('removeEditor', 'skus');
                    }
                } else {
                    $(this).datagrid('addEditor', {
                        field : 'skus',
                        editor : {
                            type : 'textbox'
                        }
                    });
                }
                if (editIndex != index) {
                    if (editIndex > -1) {
                        $(this).datagrid('endEdit', editIndex);
                    }
                    // editIndex = index;
                }
                $(this).datagrid('beginEdit', index);
                var ed = $(this).datagrid('getEditor', {index: index, field: field});
                if (ed) {
                    ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
                }
            }
        }).parent().keyup(function (event) {
            if (event.keyCode == 13) {
                MMaterielTticar.ptable.datagrid('acceptChanges').datagrid('clearSelections');
            }
            if (event.keyCode == 40) {
                appendRow();
            }
        });
    }

    // 提取规格型号
    function convertSku() {
        var arr1 = [];
        var arr2 = [];
        if (MMaterielTticar.skuIdTags.length == 0) {
            $yd.alert("当前分类没有关联规格，请在分类管理里面配置");
            return false;
        }
        $.each(MMaterielTticar.skuIdTags, function (i, n) {
            if (arr1.length == 0) {
                $.each($(n['id']).tagbox('getValues'), function (i, nn) {
                    arr1.push(n['name'] + ":" + nn);
                });
            } else {
                $.each(arr1, function (i, nn) {
                    $.each($(n['id']).tagbox('getValues'), function (i, nnn) {
                        arr2.push(nn + " " + n['name'] + ":" + nnn);
                    });
                });
                arr1 = arr2;
                arr2 = [];
            }
        });
        // console.log("规格提取结果：" + JSON.stringify(arr1));

        if (arr1.length > 0) {
            var rows = MMaterielTticar.ptable.datagrid('getRows');
            var eJson = {};
            if (rows.length > 0) { // 匹配并加载
                $yd.confirm("将覆盖现有规格？", function () {
                    $.each(rows, function (i, n) {
                        eJson[n.skus] = n;
                    });
                    MMaterielTticar.ptable.datagrid('loadData', []);
                    $.each(arr1, function (i, n) {
                        MMaterielTticar.ptable.datagrid('appendRow', $.extend({inventory: 0}, eJson[n], {skus: n}));
                    })
                })
            } else { // 直接加载自由项
                $.each(arr1, function (i, n) {
                    MMaterielTticar.ptable.datagrid('appendRow', {skus: n, inventory: 0});
                })
            }
        }
    }

    function appendRow() {
        if (editIndex > -1) {
            MMaterielTticar.ptable.datagrid('acceptChanges').datagrid('cancelEdit', editIndex);
        }
        MMaterielTticar.ptable.datagrid('appendRow', {inventory: 0}).datagrid('clearSelections');
        editIndex = MMaterielTticar.ptable.datagrid('getRows').length - 1;
        MMaterielTticar.ptable.datagrid('beginEdit', editIndex);
        var ed = MMaterielTticar.ptable.datagrid('getEditor', {index: editIndex, field: 'skus'});
        if (ed) {
            ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
        }
    }


    // $("#goodsTb").tree({
    //     url: '/carBrand/tree',
    //     cascadeCheck: false,
    //     checkbox: true,
    //     onCheck: function (node, checked) {
    //         if(checked == true) {
    //
    //         }
    //     }
    // });

    drawCarTab();
    var editIndex2 = -1;

    function drawCarTab() {
        MMaterielTticar.ctable = $('#carTab');
        MMaterielTticar.ctable.datagrid({
            url: "/carBrandMateriel/getDetailList?materielId=" + $("#id").val(),
            fitColumns: true,
            autoRowHeight: true,
            rownumbers: true,
            singleSelect: false,
            columns: [[
                {field: 'id', checkbox: true},//
                {field: 'carBrandId', hidden: true},//
                {field: 'car', title: '车型', width: 150, formatter: function (value, row, index) {
                    if(!Array.isArray(value)) {
                        value = $.parseJSON(value);
                    }
                    var result = "";
                    for(var i=0; i<value.length; i++) {
                        result += " -> " + value[i].name;
                    }
                    if(result != "") {
                        result = result.substr(4);
                    }
                    return result;
                }},
                {field: 'year', title: '出厂年月', width: 150,
                    editor: {type: 'myDate'}
                }
            ]],
            toolbar: [
                {text: '增加', iconCls: 'icon-add', handler: appendCar},
                {text: '移除', iconCls: 'icon-remove', handler: removeCar},
                {
                    text: '确定', iconCls: 'icon-save', handler: function () {
                    if (editIndex2 > -1) {
                        MMaterielTticar.ctable.datagrid('endEdit', editIndex2);
                    }
                    editIndex2 = -1;
                }
                }
            ],
            onClickCell: function (index, field) {
                if (editIndex2 != index) {
                    if (editIndex2 > -1) {
                        MMaterielTticar.ctable.datagrid('endEdit', editIndex2);
                    }
                    editIndex2 = index;
                }
                if (field == "year") {
                    MMaterielTticar.ctable.datagrid('beginEdit', index);
                }
            }
        });

        MMaterielTticar.ctable.datagrid('enableCellEditing');
    }

    function appendCar() {
        var href = "/carBrand/tree?type=0";
        var $dg = $yd.win2.create('车型', href);
        $dg.width = "450px;";
        $dg.height = "520px;";

        MMaterielTticar.dgType2 = "car";
        $dg.open(function (that, $win) {
            MMaterielTticar.win2 = $win;
            MMaterielTticar.winThat2 = that;
        }, function () {
            MMaterielTticar.saveCarBrand();
        }, function () {
            MMaterielTticar.closeDg2(1);
        });
    }

    function removeCar() {
        var rows = MMaterielTticar.ctable.datagrid('getChecked');
        if(rows.length == 0) {
            $yd.alert("选中记录");
            return;
        }

        var arr = [];
        for(var i=0; i<rows.length; i++) {
            arr[i] = rows[i].carBrandId;
        }
        for(var i=0; i<arr.length; i++) {
            var rows2 = MMaterielTticar.ctable.datagrid("getRows");
            for(var j=0; j<rows2.length; j++) {
                if(rows2[j].carBrandId == arr[i]) {
                    MMaterielTticar.ctable.datagrid("deleteRow", j);
                    break;
                }
            }
        }
    }
};

MMaterielTticar.saveCarBrand = function() {
    var result = CarTree.getChecked();
    for(var i=0; i<result.length; i++) {
        var arr = result[i];
        var carBrandId = arr.length == 0 ? 0 : arr[arr.length-1].id;
        MMaterielTticar.ctable.datagrid('appendRow', {
            car: arr,
            carBrandId: carBrandId
        }).datagrid('clearSelections');
    }
    MMaterielTticar.closeDg2(0)
};

//加载价格体系
$yd.get("/sysDict/materiel_PL", function (data) {
    MMaterielTticar.priceLv = [[]];
    MMaterielTticar.priceLv[0].push(getCol('skus', '规格/尺寸', {align: 'left',editor: 'textbox', width: 200}));
    MMaterielTticar.priceLv[0].push(getCol('partsCode', '配件编码', {align: 'left',editor: 'textbox', width: 200}));
    MMaterielTticar.priceLv[0].push(getCol('buyPrice', '参考进价', {align: 'left', editor: 'textbox', width: 100}));
    MMaterielTticar.priceLv[0].push(getCol('sellPrice', '参考零售价', {align: 'left', editor: 'textbox', width: 100}));
    // 123级会员价
    $.each(data, function (i, n) {
        MMaterielTticar.priceLv[0].push(getCol(n['value'], n['text'], {align: 'left', editor: 'textbox', width: 100}));
    });
    // loadDatagrid();
});
function getCol(field, title, options) {
    return $.extend({
        field: field,
        title: title,
        width: 120,
        align: 'right',
        resizable: true,
        editor: {type: 'numberbox', options: {precision: 2}}
    }, options);
}

function loadDatagrid() {
    var grid = new $yd.DataGrid(MMaterielTticar.dtable);
    grid.onDblClickRow = function (index, row) {
        MMaterielTticar._edit(row['id'],false);
    };
    grid.url = MMaterielTticar.uList;
    // grid.autoSizeColumn = "img";
    grid.nowrap = false;
    // grid.checkOnSelect = false;
    grid.frozenColumns = [[
        {field: 'id', checkbox: true}
        , {field: 'ctime', title: '创建时间', width: 100}
        , {field: 'name', title: '名称', width: 100}
        , {field: 'categoryName', title: '分类', width: 50}
        , {field: 'brandName', title: '品牌', width: 50}
        , {field: 'relativeName', title: '默认供应商', width: 100}
        , {field: 'car', title: '适用车型', width: 100, formatter: function (value) {
            return $yd.formatDetail(value);
        }
        }
        // , {field: 'min_inventory', title: '最低库存', width: 50}
        // , {field: 'max_inventory', title: '最高库存', width: 50}
        , {
            field: 'status', title: '状态', width: 50, formatter: function (value) {
                if (value == 0) {
                    return '<label class="label label-success">启用</label>';
                } else if (value == 1){
                    return '<label class="label label-default">禁用</label>';
                }
            }
        }
        // , {field: 'skus', title: '规格', width: 100}
        , {field: 'mskuCode', title: '编码', width: 100}

    ]];
    grid.rowStyler = function (index, row) {
        if (row.status != 0) {
            return {class: 'text-muted', style: 'text-decoration:line-through'};
        }
    };
    grid.columns = MMaterielTticar.priceLv;
    grid.loadFilter = function (data) {
        MMaterielTticar.dg.merges = {};
        data.rows = data.records;
        $.each(data.rows, function (i, n) {
            if (n.prices) $.extend(n, JSON.parse(n.prices));
            var mid = MMaterielTticar.dg.merges[n['id']];
            if (mid == undefined) {
                MMaterielTticar.dg.merges[n['id']] = {index: i, rows: 1};
            } else {
                mid.rows = mid.rows + 1;
            }
        });
        return data;
    };
    grid.onLoadSuccess = function () {
        var $this = $(this);
        $.each(MMaterielTticar.dg.merges, function (key, value) {
            var merge = {index: value.index, field: 'name', rowspan: value.rows};
            $this.datagrid('mergeCells', merge)
                .datagrid('mergeCells', $.extend(merge, {field: 'id'}))
                .datagrid('mergeCells', $.extend(merge, {field: 'categoryName'}))
                .datagrid('mergeCells', $.extend(merge, {field: 'relativeName'}))
                .datagrid('mergeCells', $.extend(merge, {field: 'max_inventory'}))
                .datagrid('mergeCells', $.extend(merge, {field: 'min_inventory'}))
                .datagrid('mergeCells', $.extend(merge, {field: 'car'}))
                .datagrid('mergeCells', $.extend(merge, {field: 'status'}))
                .datagrid('mergeCells', $.extend(merge, {field: 'brandName'}))
                // .datagrid('mergeCells', $.extend(merge, {field: 'ainventory'}))
                .datagrid('mergeCells', $.extend(merge, {field: 'ctime'}))
            ;
        });
    };/*
     grid.onEndEdit = function (index, row, changes) {
     var $this = $(this);
     if (changes) {
     // $yd.confirm("确定修改？", function () {
     //
     // })
     var sku = {};
     $.each(MMateriel.priceLv[0], function (i, n) {
     sku[n.field] = row[n.field];
     });
     var _sku = $.extend(true, {}, sku);
     delete _sku['skus'];
     delete _sku['inventory'];
     sku.prices = JSON.stringify(_sku);
     sku.id = row.skuId;
     sku.mid = row.id;
     $yd.post(MMateriel.uEditSku, sku, function () {
     $this.datagrid('reload');
     });
     }
     };*/
    grid.loadGrid();
    // MMateriel.dtable.datagrid('enableCellEditing');
}

// 提交数据
//处理规格
MMaterielTticar.pre = function (param) {

    MMaterielTticar.ptable.datagrid('acceptChanges');
    MMaterielTticar.ctable.datagrid('acceptChanges');
    var rows = MMaterielTticar.ptable.datagrid('getRows');
    // param.ainventory = 0;
    $.each(rows, function (i, n) {
        if (n) {
            // param.ainventory += parseFloat(n['inventory']) || 0;
            // var _n = $.extend(true, {}, n);
            // delete _n['id'];
            // delete _n['skus'];
            // delete _n['inventory'];
            // delete _n['buyPrice'];
            // delete _n['sellPrice'];
            // n.prices = JSON.stringify(_n);
            // 价格信息json
            var prices = {0:n['0'],1:n['1'],2:n['2'],3:n['3']};
            n.prices = JSON.stringify(prices);
        };
    });
    param.mMaterielSkuStr = JSON.stringify(rows);
    param.pictrues = MMaterielTticar.pictrues.getValues();
    param.description = MMaterielTticar._picDesc.getValue();

    param.carBrand = JSON.stringify(MMaterielTticar.ctable.datagrid('getRows'));
};

$.extend($.fn.datagrid.defaults.editors, {
    myDate: {
        init: function (container, options) {
            return $('<input id="attYearMonth" editable="false" name="attYearMonth" class="easyui-datebox" style="width: 100%" />').appendTo(container);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            return  $('#attYearMonth').datebox("getValue");
        },
        setValue: function (target, value) {
            if($yd.isEmpty(value)) {
                $('#attYearMonth').datebox("setValue", (new Date().getFullYear() - 3) + "-" + (new Date().getMonth() + 1));
            } else {
                $('#attYearMonth').datebox("setValue", value);
            }
        },
        resize: function (target, width) {
            $('#attYearMonth').datebox({
                //显示日趋选择对象后再触发弹出月份层的事件，初始化时没有生成月份层
                onShowPanel: function () {
                    //触发click事件弹出月份层
                    var p = $('#attYearMonth').datebox('panel'),
                    //日期选择对象中月份
                        tds = false,
                    //显示月份层的触发控件
                        span = p.find('span.calendar-text');

                    span.trigger('click');
                    if (!tds)
                    //延时触发获取月份对象，因为上面的事件触发和对象生成有时间间隔
                        setTimeout(function() {
                            tds = p.find('div.calendar-menu-month-inner td');
                            tds.click(function(e) {
                                //禁止冒泡执行easyui给月份绑定的事件
                                e.stopPropagation();
                                //得到年份
                                var year = /\d{4}/.exec(span.html())[0] ,
                                //月份
                                //之前是这样的month = parseInt($(this).attr('abbr'), 10) + 1;
                                    month = parseInt($(this).attr('abbr'), 10);

                                //隐藏日期对象
                                $('#attYearMonth').datebox('hidePanel')
                                    //设置日期的值
                                    .datebox('setValue', year + '-' + month);
                            });
                        }, 0);
                },
                //配置parser，返回选择的日期
                parser: function (s) {
                    if (!s) return new Date();
                    var arr = s.split('-');
                    return new Date(parseInt(arr[0], 10), parseInt(arr[1], 10) - 1, 1);
                },
                //配置formatter，只返回年月 之前是这样的d.getFullYear() + '-' +(d.getMonth());
                formatter: function (d) {
                    var currentMonth = (d.getMonth()+1);
                    var currentMonthStr = currentMonth < 10 ? ('0' + currentMonth) : (currentMonth + '');
                    return d.getFullYear() + '-' + currentMonthStr;
                }
            });

            $(target)._outerWidth(width);
        }
    }
});